package com.hbun.cxcy.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hbun.cxcy.common.utils.R;
import com.hbun.cxcy.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        try {
            String token = request.getHeader("token");
            if (token == null) {
                token = request.getParameter("token");
            }
            if (!StringUtils.isEmpty(token)) {
                Claims claims = JWTUtils.checkJWT(token);
                if (claims == null) {
                    // 说明登录过期
                    sendJsonMessage(response,R.error("登录过期，请重新登录"));
                    return false;
                }
                Integer id = (Integer) claims.get("id");
                String userName = (String) claims.get("userName");
                request.setAttribute("id",id);
                request.setAttribute("user_name",userName);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        sendJsonMessage(response,R.error("登录过期，请重新登录"));
        return false;
    }

    public static void sendJsonMessage(HttpServletResponse response, Object obj) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.print(objectMapper.writeValueAsString(obj));
            writer.close();
            response.flushBuffer();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}